﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net.Http.Json;
namespace ParkSaleFeatureDemo
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        safe_User Logined;

        public static string address = "https://localhost:44338/";
        static string MakeLoginHttpUri(string user, string pass)
        {
            return $"{address}Login?username={user}&password={pass}";
        }
        static string MakeFindUserHttpUri(string user)
        {
            return $"{address}GetUser?username={user}";
        }
        static string MakeMessageGetHttpUri(string user)
        {
            return $"{address}RequestMessages?id={user}";
        }
        static string MakeMessageReplyHttpUri(int id)
        {
            return $"{address}ReplyMessage?id={id}";
        }
        AsyncTask task = new AsyncTask();
        public MainWindow()
        {
            InitializeComponent();
        }
        HttpClient client = new HttpClient();

        [Serializable]
        public class PublicMessage
        {
            public int ID
            {
                get;
                set;
            }
            public DateTime Time
            {
                get;
                set;
            }
            public string Content
            {
                get;
                set;
            }
            public string From
            {
                get;
                set;
            }
            public bool Handled
            {
                get;
                set;
            }
            public string To
            {
                get;
                set;
            }
        }

        [System.Serializable]
        public class safe_User
        {
            /// <summary>
            /// 用户身份证号
            /// </summary>
            public string ID
            {
                get;
                set;
            }
            /// <summary>
            /// 用户名
            /// </summary>
            public string UserName
            {
                get;
                set;
            }
            /// <summary>
            /// 用户手机号
            /// </summary>
            public string Phone
            {
                get;
                set;
            }
            public override string ToString()
            {
                return $"Welcome {UserName}, Your ID is {ID},Phone Is {Phone}";
            }
        }
        [Serializable]
        public class FullMessage : PublicMessage
        {
            public string Type
            {
                get;
                set;
            }

            public string Arg
            {
                get;
                set;
            }
        }
        void ReadMessage()
        {
            task.Run(delegate () {
               var t= client.GetFromJsonAsync<FullMessage[]>(MakeMessageGetHttpUri(Logined.ID));
                t.Wait();
                return t.Result;
            },delegate(object ob) {
                FullMessage[] messages = (FullMessage[])ob;
                foreach (var i in messages)
                {
                    ListBoxItem item = new ListBoxItem() { Tag = i, Content = $"{i.Content} From {i.From} Time {i.Time}  IsHandle {i.Handled}, Type {i.Type}" };
                    listBox.Items.Add(item);
                }
            });


        }


        private void login_Click(object sender, RoutedEventArgs e)
        {
            login.IsEnabled = false;
            string id = username.Text;
            string pass = password.Password;
            task.Run(delegate () {
                
                var t= client.GetAsync(MakeLoginHttpUri(id, pass));
                t.Wait();
                var read= t.Result.Content.ReadAsStringAsync();
                read.Wait();
                return read.Result;
            }, delegate (object obj) {
                switch (int.Parse(obj.ToString()))
                {
                    case 1:
                        task.Run(delegate ()
                        {
                            var t = client.GetAsync(MakeFindUserHttpUri(id));
                            t.Wait();
                           var re= t.Result.Content.ReadFromJsonAsync<safe_User>();
                            re.Wait();
                           return re.Result;
                        }, delegate (object o) {
                            MessageBox.Show(((safe_User)o).ToString(), "欢迎");
                            Logined = (safe_User)o;
                            Title = Logined.ID;
                            ReadMessage();
                        });
                        break;
                    case 0:
                        MessageBox.Show("密码错误", "错误");
                        break;
                    case -1:
                        MessageBox.Show("用户名错误", "错误");
                        break;
                }

            });
            login.IsEnabled = false;
        }

        private void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                var item = (ListBoxItem)listBox.SelectedItem;
                if (item != null)
                {
                    var msg = (FullMessage)item.Tag;
                    if (msg != null)
                    {
                        if (msg.Type.Equals("DiscountPicker"))
                        {
                            dealer.IsEnabled = true;
                        }
                        else
                        {
                            dealer.IsEnabled = false;
                        }
                    }

                }

            }
            catch
            {
                
            }

        }

        private void dealer_Click(object sender, RoutedEventArgs e)
        {
            var item = (ListBoxItem)listBox.SelectedItem;
            var msg = (FullMessage)item.Tag;
            MessageBoxResult result= MessageBox.Show("是否接收？", "输入",MessageBoxButton.YesNoCancel);
            switch (result)
            {
                case MessageBoxResult.Yes:
                    task.Run(delegate () {
                       var t= client.PostAsync(MakeMessageReplyHttpUri(msg.ID), JsonContent.Create("1", typeof(string)));
                        t.Wait();
                      var r=  t.Result.Content.ReadAsStringAsync();
                        r.Wait();
                        return r.Result ;
            },delegate(object o) {
               int resultcode= int.Parse(o.ToString());
                if (resultcode > 0)
                {
                    MessageBox.Show($"处理成功 {resultcode}");
                    listBox.Items.Clear();
                    ReadMessage();
                }
                else
                {
                    MessageBox.Show($"处理失败 {resultcode}");
                }
            });
                    break;
                case MessageBoxResult.No:
                    break;
                case MessageBoxResult.Cancel:
                    break;
            }

        }
    }
}
